const router = require('koa-router')()
const crypto = require('crypto');
router.prefix('/manager')

router.get('/', async (ctx, next) => {
    let userName = ctx.query.user;
    let page = parseInt(ctx.query.page);
    let size = parseInt(ctx.query.size);
    let selectUser = "select userId, userName, realName, organizationName, roleType from loginuser left join organization on loginuser.organizationId=organization.organizationId left" 
        +   " join roles on loginuser.roleId=roles.roleId ORDER BY userId DESC LIMIT ? OFFSET ?;";

    let userList = await ctx.db.EXECUTE(selectUser, size, size * (page - 1));

    let countSql = "select count(*) as total from loginuser";
    let countResult = await ctx.db.EXECUTE(countSql);


    if(userList.length > 0) {
        ctx.body = {
            status: 'ok',
            userList: userList,
            total: countResult[0].total
        }
    }
})


router.post('/add', async (ctx, next) => {
    let {realName, userName, pwd, organizationId, roleId} = ctx.request.body;
    let selectSql = "select * from loginuser where userName=?";
    let selectResult = await ctx.db.EXECUTE(selectSql, userName);
    if(selectResult.length > 0) {
        ctx.body = {
            status: 'invalid'
        }
    }
    else {
        let md5 = crypto.createHash("md5");
        let newPas = md5.update(pwd).digest("hex");
        let insertSql = "insert into loginuser (realName, userName, pwd, organizationId, roleId) values(?, ?, ?, ?, ?)";
        let result = await ctx.db.EXECUTE(insertSql, realName, userName, newPas, organizationId, roleId);
        if(result.affectedRows > 0) {
            ctx.body = {
                status: 'ok'
            }
        }
    }
})


router.post('/update', async (ctx, next) => {
    let {userId, realName, userName, pwd, organizationId, roleId} = ctx.request.body;
    let selectSql = "select * from loginuser where userName=? and userId!=?";
    let selectResult = await ctx.db.EXECUTE(selectSql, userName, userId);
    if(selectResult.length > 0) {
        ctx.body = {
            status: 'invalid'
        }
    }
    else {
        let insertSql = "update loginuser set realName=?, userName=?, organizationId=?, roleId=? where userId=?";
        let result = await ctx.db.EXECUTE(insertSql, realName, userName, organizationId, roleId, userId);
        if(result.affectedRows > 0) {
            ctx.body = {
                status: 'ok'
            }
        }
    }
})

router.post('/del', async (ctx, next) => {
    let { userId } = ctx.request.body;
    let delSql = "delete from loginuser where userId=?";
    let result = await ctx.db.EXECUTE(delSql, userId);
    if(result.affectedRows > 0) {
        ctx.body = {
            status: 'ok'
        }
    }
})



module.exports = router
